//请求拦截器
// dus
//dui 所有的请求进行处理
//1.路径拼接
//2.超时设置
//3.请求头标识

import { UseMemberStore } from '@/store'
const BaseUrl = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'
//4.token
const httpInterceptor = {
  invoke(options: UniApp.RequestOptions) {
    // request 触发前拼接 url
    options.url = BaseUrl + options.url
    //
    options.timeout = 10000
    options.header = {
      ...options.header,
      'source-client': 'miniapp',
    }
    const userStore = UseMemberStore()
    const token = userStore.profile?.token
    if (token) {
      options.header.Authorization = token
    }
  },
}

uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

interface Data<T> {
  code: string
  msg: string
  result: T
}

//数据处理
export const http = <T>(options: UniApp.RequestOptions) => {
  return new Promise<Data<T>>((reslove, reject) => {
    //发请求
    uni.request({
      ...options,
      success(res: any) {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          reslove(res.data as Data<T>)
        } else if (res.statusCode === 401) {
          const userStore = UseMemberStore()
          userStore.clearProfile()
          uni.navigateTo({ url: '/pages/login/login' })
          reject(res)
        } else {
          uni.showToast({
            title: res.data.msg || '数据获取失败',
            icon: 'none',
            mask: true,
          })
          reject(res)
        }
      },
      fail(err: any) {
        uni.showToast({
          title: '网络错误,换个网试试',
          icon: 'none',
        })
        reject(err)
      },
    })
  })
}
